//
//  OAuthViewController.swift
//  MyWeiboApp
//
//  Created by 胡海波 on 15/6/27.
//  Copyright © 2015年 胡海波. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class OAuthViewController: UIViewController,UIWebViewDelegate {

    // 定义常量
    private let WB_Client_ID = "3803193155"
    private let WB_Redirect_URI = "http://www.baidu.com"
    private let WB_App_Secret = "c05b1cd320c819a2cd65944c1dd2d06c"

    // 懒加载
    lazy var webView: UIWebView? = {

        let wv = UIWebView()
        wv.delegate = self
        return wv
    }()

    override func loadView() {

        // 根视图设为webView
        view = webView


        title = "新浪微博"
        // 设置UIBarbuttonItem
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    }

    func close() {

         SVProgressHUD.dismiss()

        dismissViewControllerAnimated(true,completion:nil)


    }




    override func viewDidLoad() {
        super.viewDidLoad()

        loadOAuthPage()


    }

    private func loadOAuthPage() {

        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_Client_ID)&redirect_uri=\(WB_Redirect_URI)"

        let url = NSURL(string: urlString)!

        webView?.loadRequest(NSURLRequest(URL: url))
    }

    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {

        let urlString = request.URL!.absoluteString
        print(urlString)

        // 如果不是回调的 url，就继续加载
        if !urlString.hasPrefix(WB_Redirect_URI) {
            return true
        }

        // 如果是回调地址，需要根据url中的内容，判断是否有授权码

        // 获取请求URL中的查询字符串
        let query = request.URL!.query!
        let codeStr = "code="

        // 判断是否包含 code＝
        if query.hasPrefix(codeStr){
            let code = query.substringFromIndex(advance(codeStr.endIndex, 0))

            print("获取授权码 \(code)")

            loadAccessToken(code)
        }
        else {
            print("取消授权")

            close()
        }

        return false
    }


    func webViewDidStartLoad(webView: UIWebView) {

        SVProgressHUD.show()
    }

    func webViewDidFinishLoad(webView: UIWebView) {

        SVProgressHUD.dismiss()
    }

    ///  使用授权码加载token
    private func loadAccessToken(code:NSString){

        let urlString = "oauth2/access_token"
        // 请求参数
        let params = ["client_id":WB_Client_ID,"client_secret":WB_App_Secret,"grant_type":"authorization_code","code":code,"redirect_uri":WB_Redirect_URI]

        // 发送网络请求
        NetWorkingTools.shareNetworkTools().POST(urlString, parameters: params, success: { (_, JSON) -> Void in

            print(JSON)

            UserAccount(dict: JSON as! [String: AnyObject]).loadUserInfo { (account,error) -> () in

                if account != nil {

                    print(account)

                    // 设置全局的account
                    sharedUserAccount = account

                    NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootVCNotification, object: false)

                    // 关闭当前控制器
                    self.close()

                    return
                }

                print(error)

                SVProgressHUD.showInfoWithStatus("你的网速不给力")

            }


            }) { (_, error) -> Void in

                SVProgressHUD.showInfoWithStatus("你的网速不给力")
        }
    }

    deinit{

        print("我去了---------")

    }

}
